<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="1200px"
    :close-on-click-modal="false"
    :modal-append-to-body="false"
    :append-to-body="true"
    :destroy-on-close="true"
    :before-close="handleClose"
  >
    <el-row>
      <el-col :span="12">
        <el-card header="基础配置">
          <el-form
            ref="columnEdit"
            :model="column"
            :rules="rules"
            label-width="150px"
          >
            <el-form-item v-if="tableType === 1" label="所属组别" prop="GroupId">
              <el-cascader
                v-model="column.GroupId"
                placeholder="所属组别"
                :clearable="true"
                :props="{
                  emitPath: false,
                  label: 'Name',
                  value: 'Id',
                  children: 'Children'
                }"
                :options="groups"
              />
            </el-form-item>
            <el-form-item v-if="tableType === 1 && sourItems.length > 0" label="数据源" prop="ColAliasName">
              <el-select v-model="column.ColAliasName" placeholder="选择数据源">
                <el-option
                  v-for="item in sourItems"
                  :key="item.ItemCode"
                  :label="item.ItemName"
                  :value="item.ItemCode"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="标题" prop="ColTitle">
              <el-input
                v-model="column.ColTitle"
                :maxlength="50"
                placeholder="标题"
                @change="titleChange"
              />
            </el-form-item>
            <el-form-item label="列名" prop="ColName">
              <el-input
                v-model="column.ColName"
                :maxlength="50"
                placeholder="列名"
              />
            </el-form-item>
            <el-form-item label="控件" prop="ControlId">
              <controlSelect
                v-model="column.ControlId"
                :control.sync="control"
                placeholder="选择控件"
                @load="intiControl"
                @change="intiControl"
              />
            </el-form-item>
            <el-form-item label="提示信息" prop="Description">
              <el-input
                v-model="column.Description"
                :maxlength="50"
                placeholder="提示信息"
              />
            </el-form-item>
            <el-form-item label="必填" prop="IsNotNull">
              <el-switch
                v-model="column.IsNotNull"
                active-text="不能为空"
                inactive-text="可为空"
              />
            </el-form-item>
            <el-form-item label="默认值类型" prop="DefValType">
              <enumItem
                v-model="column.DefValType"
                :dic-key="EnumDic.FormDefValType"
                sys-head="form"
                placeholder="默认值类型"
              />
            </el-form-item>
            <el-form-item v-if="column.DefValType == 0" label="默认值" prop="DefaultVal">
              <defValueSet v-if="control" :key="control.Id" v-model="column.DefaultVal" :control="control" :control-set="contSet" :is-load="control && column.DefValType == 0 && isInit" />
            </el-form-item>
            <el-form-item v-else-if="column.DefValType == 1" label="公式" prop="Formula">
              <formulaInput v-model="column.Formula" :clearable="true" :field-list="formBody" />
            </el-form-item>
            <el-form-item label="默认显示状态" prop="DefState">
              <enumItem
                v-model="column.DefState"
                :dic-key="EnumDic.FormStateControl"
                sys-head="form"
                placeholder="默认显示状态"
              />
            </el-form-item>
            <el-form-item label="只读时以Label展示" prop="IsLabel">
              <el-switch
                v-model="column.IsLabel"
                active-text="是"
                inactive-text="否"
              />
            </el-form-item>
            <el-form-item label="显示状态公式" prop="StateFormula">
              <formulaInput v-model="column.StateFormula" :clearable="true" :field-list="formBody" />
            </el-form-item>
            <el-form-item v-if="column.StateFormula" label="满足条件后" prop="StateControl">
              <enumItem
                v-model="column.StateControl"
                :dic-key="EnumDic.FormStateControl"
                sys-head="form"
                placeholder="满足条件后显示状态"
              />
            </el-form-item>
            <template v-if="tableType == 1">
              <el-form-item label="对齐方式" prop="ColAlign">
                <enumItem
                  v-model="column.Align"
                  :dic-key="EnumDic.ColAlign"
                  sys-head="form"
                  placeholder="对齐方式"
                />
              </el-form-item>
              <el-form-item label="列最小宽" prop="Width">
                <el-input-number
                  v-model="column.Width"
                  :precision="0"
                  placeholder="列最小宽"
                />
              </el-form-item>
              <el-form-item label="是否是合并行" prop="IsMergeRow">
                <el-switch
                  v-model="column.IsMergeRow"
                  active-text="是"
                  inactive-text="否"
                />
              </el-form-item>
              <el-form-item label="固定显示类型" prop="FiexdType">
                <enumItem
                  v-model="column.FiexdType"
                  :dic-key="EnumDic.FiexdType"
                  sys-head="form"
                  placeholder="固定显示类型"
                />
              </el-form-item>
            </template>
          </el-form>
        </el-card>
      </el-col>
      <el-col :span="11" :offset="1">
        <controlSet v-if="control" :key="control.Id" ref="controlSet" :control="control" :control-set.sync="contSet" :form-body="formBody" :is-load="isInit" />
        <el-card
          v-if="ruleColType.includes(colType)"
          style="margin-top: 10px"
        >
          <div slot="header" style="line-height: 30px;">
            <span style="font-size: 1rem;">数据校验规则</span>
            <el-button type="success" size="mini" style="float: right;" @click="addRule">添加校验规则</el-button>
          </div>
          <div v-for="item in validateRule" :key="item.id" class="rule">
            <span :class="item.IsWarn ? 'warn' : 'error'" />
            <el-button type="text" @click="setRule(item)">{{ item.Message }}</el-button>
            <el-button type="text" style="float: right;color: red;" icon="el-icon-delete" @click="dropRule(item)" />
          </div>
        </el-card>
      </el-col>
    </el-row>
    <div slot="footer" style="text-align: center">
      <el-button type="primary" @click="save">保存</el-button>
      <el-button @click="resetForm">重置</el-button>
    </div>
    <editRule :visible.sync="ruleVisible" :rule.sync="rule" @close="closeRule" />
  </el-dialog>
</template>

<script>
import { pinyin } from 'pinyin-pro'
import * as columnApi from '@/customForm/api/column'
import controlSelect from '@/customForm/components/control/controlSelect.vue'
import { ControlType, EnumDic } from '@/customForm/config/formConfig'
import { GetItems } from '@/customForm/api/formSource'
import editRule from './editRule.vue'
import defValueSet from './defValueSet.vue'
import controlSet from './controlSet.vue'
import formulaInput from '@/customForm/components/formula/formulaInput.vue'
export default {
  components: {
    controlSelect,
    editRule,
    defValueSet,
    controlSet,
    formulaInput
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    formBody: {
      type: Array,
      default: null
    },
    table: {
      type: Object,
      default: null
    },
    id: {
      type: String,
      default: null
    },
    formId: {
      type: String,
      default: null
    },
    columns: {
      type: Array,
      default: () => []
    },
    groupId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      EnumDic,
      ControlType,
      ruleColType: [
        ControlType.input.value,
        ControlType.number.value,
        ControlType.text.value
      ],
      source: null,
      title: '编辑控件配置',
      ver: 1,
      isInit: false,
      column: {},
      contSet: {},
      validateRule: [],
      tableType: 0,
      ruleId: 1,
      groups: [],
      rules: {
        ColTitle: [
          {
            required: true,
            message: '标题不能为空！',
            trigger: 'blur'
          }
        ],
        ColName: [
          {
            required: true,
            message: '列名不能为空！',
            trigger: 'blur'
          }
        ],
        ControlId: [
          {
            required: true,
            message: '请选择控件！',
            trigger: 'blur'
          }
        ]
      },
      isText: false,
      control: {},
      colType: null,
      rule: null,
      ruleVisible: false,
      sourItems: []
    }
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.$nextTick(this.reset)
        } else {
          this.isInit = false
          this.contSet = null
          this.colType = null
          this.control = null
          this.source = null
        }
      },
      immediate: true
    }
  },
  mounted() {},
  methods: {
    async initSourItem() {
      if (this.table.SourceKey != null && this.table.SourceKey !== '') {
        this.sourItems = await GetItems(this.table.SourceKey)
      } else {
        this.sourItems = []
      }
    },
    addRule() {
      this.rule = null
      this.ruleVisible = true
    },
    initColumns(groups, data) {
      if (groups == null || groups.length === 0) {
        return
      }
      groups.forEach(a => {
        if (a.IsGroup) {
          const g = {
            Id: a.Id,
            Name: a.Title,
            Children: null
          }
          this.initColumns(a.Children, g)
          data.Children.push(g)
        }
      })
    },
    initGroup() {
      const list = []
      this.columns.forEach(a => {
        if (a.IsGroup) {
          const g = {
            Id: a.Id,
            Name: a.Title,
            Children: null
          }
          this.initColumns(a.Children, g)
          list.push(g)
        }
      })
      this.groups = list
    },
    dropRule(row) {
      const index = this.validateRule.findIndex(a => a.id === row.id)
      this.validateRule.splice(index, 1)
    },
    closeRule(op) {
      if (op === 'add') {
        this.rule.id = this.ruleId
        this.ruleId = this.ruleId + 1
        this.validateRule.push(this.rule)
      }
    },
    setRule(row) {
      this.rule = row
      this.ruleVisible = true
    },
    intiControl() {
      if (this.control == null) {
        return
      }
      this.colType = this.control.ControlType
      if (this.source != null) {
        this.resetDefValue()
      }
      const data = this.column.ControlSet == null ? {} : this.column.ControlSet
      if (this.control.Config != null && this.control.Config.length !== 0) {
        this.control.Config.forEach((c) => {
          // eslint-disable-next-line no-prototype-builtins
          if (!data.hasOwnProperty(c.Key)) {
            if (c.DefValue == null) {
              data[c.Key] = null
            } else if (c.Type === 3) {
              data[c.Key] = c.DefValue === 'true'
            } else {
              data[c.Key] = c.DefValue
            }
          }
        })
      }
      this.contSet = data
      this.isInit = this.visible
    },
    resetDefValue() {
      if (this.control.Id !== this.source.ControlId) {
        this.column.DefValType = 0
        this.column.DefaultVal = null
        this.column.DataSourceId = null
        this.column.Formula = null
      } else {
        this.column.DefValType = this.source.DefValType
        this.column.DefaultVal = this.source.DefaultVal
        this.column.DataSourceId = this.source.DataSourceId
        this.column.Formula = this.source.Formula
      }
    },
    resetForm() {
      this.column = Object.assign({}, this.source)
      this.initSourItem()
      this.initRule()
      // this.intiControl()
    },
    async reset() {
      this.tableType = this.table.TableType
      if (this.tableType === 1) {
        this.initGroup()
      }
      if (this.id != null) {
        const res = await columnApi.Get(this.id)
        this.title = '编辑控件(' + res.ColTitle + ')配置'
        this.source = res
      } else {
        this.title = '新增控件'
        this.source = {
          GroupId: this.groupId,
          ControlId: null,
          ColName: null,
          DefValType: 0,
          DataSourceId: null,
          Formula: null,
          DataType: null,
          ColTitle: null,
          Align: 1,
          ColAliasName: null,
          Description: null,
          IsNotNull: false,
          IsLabel: true,
          DefaultVal: null,
          IsMergeRow: false,
          Width: null
        }
      }
      this.ver = this.ver + 1
      this.resetForm()
      this.intiControl()
    },
    initRule() {
      const rules = []
      if (this.column.ValidateRule != null) {
        this.column.ValidateRule.forEach((c) => {
          c.id = this.ruleId
          rules.push(c)
          this.ruleId = this.ruleId + 1
        })
      }
      this.validateRule = rules
    },
    titleChange() {
      this.column.ColName = pinyin(this.column.ColTitle, {
        pattern: 'first',
        toneType: 'none',
        separator: ''
      })
    },
    handleClose() {
      this.$emit('update:visible', false)
      this.$emit('close', false)
    },
    formatControlSet() {
      this.contSet = this.$refs.controlSet.getValue()
      if (this.contSet.maxLength === 0) {
        delete this.contSet.maxLength
      }
      if (this.contSet.rows === 0) {
        delete this.contSet.rows
      }
    },
    format() {
      if (this.contSet.maxLength === 0) {
        this.contSet.maxLength = null
      }
      return {
        ControlId: this.column.ControlId,
        GroupId: this.column.GroupId,
        ColName: this.column.ColName,
        ColTitle: this.column.ColTitle,
        ColAliasName: this.column.ColAliasName,
        Description: this.column.Description,
        ColType: this.control.ControlType,
        IsNotNull: this.column.IsNotNull,
        IsLabel: this.column.IsLabel,
        DefValType: this.column.DefValType,
        Formula: this.column.Formula,
        DataSourceId: this.column.DataSourceId,
        DefaultVal: this.column.DefaultVal,
        Width: this.column.Width === 0 ? null : this.column.Width,
        IsMergeRow: this.column.IsMergeRow,
        FiexdType: this.column.FiexdType,
        Align: this.column.Align,
        EditControl: this.control.EditControl,
        ControlSet: this.contSet,
        StateFormula: this.column.StateFormula,
        StateControl: this.column.StateControl,
        DefState: this.column.DefState,
        ValidateRule: this.validateRule.map(c => {
          const t = Object.assign({}, c)
          delete t.id
          return t
        })
      }
    },
    async set() {
      this.formatControlSet()
      const data = this.format()
      const isSet = await columnApi.Set(this.id, data)
      this.$emit('update:visible', false)
      this.$emit('close', isSet, data)
    },
    async add() {
      this.formatControlSet()
      const data = this.format()
      data.FormId = this.formId
      data.TableId = this.table.Id
      data.ColSpan = 1
      const id = await columnApi.AddFull(data)
      data.Id = id
      this.$emit('update:visible', false)
      this.$emit('close', true, data)
    },
    save() {
      this.$refs['columnEdit'].validate((valid) => {
        if (valid) {
          if (this.id == null) {
            this.add()
          } else {
            this.set()
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style scoped>
.rule {
  width: 100%;
  line-height: 20px;
}
.rule .warn {
  display: inline-block;
  width: 10px;
  height: 10px;
  background-color:rgb(235, 181, 99);
  margin-right: 5px;
  border-radius: 20px;
}
.rule .error {
  display: inline-block;
  width: 10px;
  height: 10px;
  background-color: #e4393c;
  margin-right: 5px;
  border-radius: 20px;
}
</style>
